package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.service.UserSerivce;
import com.itheima.reggie.utils.ValidateCodeUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author ck
 * @date 2021/10/18 9:23
 */
@RestController
@RequestMapping("/user")
@Slf4j
@Api(tags = "用户相关接口")
public class UserController {

    @Autowired
    private UserSerivce userSerivce;

    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping("/sendMsg")
    @ApiOperation("发送短信接口")
    public R<String> sendMsg(@RequestBody User user, HttpSession session){
        //手机号
        String phone = user.getPhone();
        //生成随机验证码
        String code = ValidateCodeUtils.generateValidateCode(4).toString();
        log.info("验证码：{}",code);
        //发送短信
//        SMSUtils.sendMessage("菩提阁","SMS_159820392",phone,code);
        //将验证码存入Session，方便后续登录时比对
//        session.setAttribute(phone,code);

        //将生成的验证码缓存到redis中,并且设置有效期为5分钟
        ValueOperations valueOperations = redisTemplate.opsForValue();
        valueOperations.set(phone,code,5, TimeUnit.MINUTES);
        return R.success(code);
    }

    @PostMapping("/login")
    @ApiOperation("用户登录接口")
    public R<User> login(@RequestBody Map map,HttpSession session){
        R<User> login = userSerivce.login(map, session);
        return login;
    }

    @PostMapping("/loginout")
    @ApiOperation("用户退出接口")
    public R<String> loginout(HttpServletRequest request){
        //清理Session中保存的当前登录用户的id
        request.getSession().removeAttribute("user");
        return R.success("退出成功");
    }
}
